package com.yiren.dbaa.module.project_edit.view.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yiren.backstage.config.api.LoadConfigApi;
import com.yiren.backstage.config.enums.ExamUiEnum;
import com.yiren.backstage.config.enums.PlayOrderEnum;
import com.yiren.backstage.config.enums.SiteConfigCodeEnum;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.entity.LineInfoEntity;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.db.dao.bean.SynExamBean;
import com.yiren.backstage.db.dao.cache.ProjectCache;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.currency.model.CheckBoxCommonModel;
import com.yiren.dbaa.currency.model.EdittextCommonModel;
import com.yiren.dbaa.module.project_edit.contract.SiteInfoSetContract;
import com.yiren.dbaa.module.project_edit.presenter.SiteInfoSetPresenter;
import com.yiren.dbaa.module.project_edit.view.dialog.SiteInfoDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lwb
 * on 2021/12/29
 * Describe  练车设置Fragment
 */
public class SiteInfoSetFragment extends Fragment implements SiteInfoSetContract.View {

    @BindView(R.id.tv_exam_surface)
    TextView tvExamSurface;
    @BindView(R.id.tv_sczb_next_project)
    TextView tvSczbNextProject;
    @BindView(R.id.tv_mndg_next_project)
    TextView tvMndgNextProject;
    @BindView(R.id.et_train_mileage)
    EditText etTrainMileage;
    @BindView(R.id.cb_auto_play_kbtc)
    CheckBox cbAutoPlayKbtc;
    @BindView(R.id.cb_kbtc_distance)
    CheckBox cbKbtcDistance;
    @BindView(R.id.cb_kbtc_project)
    CheckBox cbKbtcProject;
    @BindView(R.id.cb_exe_one_project)
    CheckBox cbExeOneProject;
    @BindView(R.id.et_start_voice)
    EditText etStartVoice;
    @BindView(R.id.cb_no_play_project)
    CheckBox cbNoPlayProject;
    @BindView(R.id.et_autoplay_distance)
    EditText etAutoplayDistance;
    @BindView(R.id.cb_random_play_line)
    CheckBox cbRandomPlayLine;
    @BindView(R.id.cb_pass_no_play)
    CheckBox cbPassNoPlay;
    @BindView(R.id.et_pass_voice)
    EditText etPassVoice;
    @BindView(R.id.et_no_pass_voice)
    EditText etNoPassVoice;
    @BindView(R.id.et_end_voice)
    EditText etEndVoice;
    @BindView(R.id.cb_no_pass_play)
    CheckBox cbNoPassPlay;
    @BindView(R.id.tv_play_order)
    TextView tvPlayOrder;
    @BindView(R.id.et_end_exam_voice)
    EditText etEndExamVoice;
    @BindView(R.id.cb_speed_count)
    CheckBox cbSpeedCount;
    @BindView(R.id.et_speed_count)
    EditText etSpeedCount;
    @BindView(R.id.cb_12gear_dis)
    CheckBox cb12gearDis;
    @BindView(R.id.cb_12gear_dis_noclutch)
    CheckBox cb12gearDisNoclutch;
    @BindView(R.id.cb_gear_speed)
    CheckBox cbGearSpeed;
    @BindView(R.id.et_gear_count)
    EditText etGearCount;
    @BindView(R.id.et_gear_speed)
    EditText etGearSpeed;
    @BindView(R.id.cb_speed_count_c2)
    CheckBox cbSpeedCountC2;
    @BindView(R.id.et_speed_count_c2)
    EditText etSpeedCountC2;

    /*** 初始值 */
    private ExamUiEnum examUi;
    private String sczbNextProject;
    private String mndgNextProject;
    private PlayOrderEnum playOrder;
    private int chooseValueC1;
    private int chooseValueC2;

    private SiteEntity site;
    /*** 存放参数值改变的临时map */
    private Map<String, Object> tempMap;
    private boolean isPartner;
    private SynExamBean synExamBean;
    private List<EdittextCommonModel> edittextCommonModels;
    private List<CheckBoxCommonModel> checkBoxCommonModels;

    private SiteInfoSetContract.Presenter presenter;
    private Gson gs = new Gson();
    private SiteInfoDialog siteInfoDialog;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_siteinfo_set, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
        setData();
        setEditText();
        setCheckBox();
    }

    private void initData() {
        site = (SiteEntity) getArguments().getSerializable("site");
        presenter = new SiteInfoSetPresenter(getActivity());
        tempMap = new HashMap<>();
        isPartner = LoadConfigApi.loadUserParamConfig(getActivity()).isPartner();
        synExamBean = gs.fromJson(isPartner ? site.getPartneModifyVal() : site.getCoachModifyVal(), new TypeToken<SynExamBean>() {
        }.getType());
        if (null == synExamBean) synExamBean = new SynExamBean();
        siteInfoDialog = new SiteInfoDialog(getActivity());
    }

    private void setData() {
        //考车界面
        examUi = ExamUiEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L1.toString()));
        tvExamSurface.setText(examUi.getDescription());
        //上车准备接下来的项目
        sczbNextProject = (String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L2.toString());
        tvSczbNextProject.setText((sczbNextProject.equals("0") || null == ProjectCache.getPointById(sczbNextProject)) ? "不执行" : ProjectCache.getPointById(sczbNextProject).getName());
        //模拟灯光接下来的项目
        mndgNextProject = (String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L3.toString());
        tvMndgNextProject.setText((mndgNextProject.equals("0") || null == ProjectCache.getPointById(mndgNextProject)) ? "不执行" : ProjectCache.getPointById(mndgNextProject).getName());
        //播报顺序
        playOrder = PlayOrderEnum.valueOf((String) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L19.toString()));
        tvPlayOrder.setText(playOrder.getDescription());
        chooseValueC1 = (int) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L21.toString());
        setShowC1Status(chooseValueC1);
        chooseValueC2 = (int) SignalGConstant.examConfigMap.get(SiteConfigCodeEnum.L25.toString());
        setShowC2Status(chooseValueC2);
    }

    /**
     * 设置编辑框
     */
    private void setEditText() {
        edittextCommonModels = new ArrayList<>();
        //训练里程
        edittextCommonModels.add(new EdittextCommonModel(etTrainMileage, SiteConfigCodeEnum.L4.toString()));
        //开始考试语音
        edittextCommonModels.add(new EdittextCommonModel(etStartVoice, SiteConfigCodeEnum.L11.toString()));
        //自动播报提前多少米播报档位
        edittextCommonModels.add(new EdittextCommonModel(etAutoplayDistance, SiteConfigCodeEnum.L13.toString()));
        //成绩合格播报语音
        edittextCommonModels.add(new EdittextCommonModel(etPassVoice, SiteConfigCodeEnum.L15.toString()));
        //成绩不合格播报语音
        edittextCommonModels.add(new EdittextCommonModel(etNoPassVoice, SiteConfigCodeEnum.L16.toString()));
        //最后播报语音
        edittextCommonModels.add(new EdittextCommonModel(etEndVoice, SiteConfigCodeEnum.L17.toString()));
        //结束考试播报语音
        edittextCommonModels.add(new EdittextCommonModel(etEndExamVoice, SiteConfigCodeEnum.L20.toString()));
        //C1车速大于？码
        edittextCommonModels.add(new EdittextCommonModel(etSpeedCount, SiteConfigCodeEnum.L22.toString()));
        //？档以上车速大于？码
        edittextCommonModels.add(new EdittextCommonModel(etGearCount, SiteConfigCodeEnum.L23.toString()));
        edittextCommonModels.add(new EdittextCommonModel(etGearSpeed, SiteConfigCodeEnum.L24.toString()));
        //C2车速大于？码
        edittextCommonModels.add(new EdittextCommonModel(etSpeedCountC2, SiteConfigCodeEnum.L26.toString()));
        for (EdittextCommonModel model : edittextCommonModels) {
            model.getEt().setText(model.getInitValue());
            model.getEt().addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    SignalGConstant.examConfigMap.put(model.getKey(), s.toString());
                    if (!s.toString().equals(model.getInitValue())) {
                        tempMap.put(model.getKey(), s.toString());
                    } else {
                        tempMap.remove(model.getKey());
                    }
                }
            });
        }
    }

    /**
     * 设置CheckBox
     */
    private void setCheckBox() {
        checkBoxCommonModels = new ArrayList<>();
        //达到里程自动靠边停车
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbAutoPlayKbtc, SiteConfigCodeEnum.L5.toString()));
        //未达到里程不能靠边停车
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbKbtcDistance, SiteConfigCodeEnum.L6.toString()));
        //项目没完成，不能靠边停车
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbKbtcProject, SiteConfigCodeEnum.L7.toString()));
        //选中项目执行一次
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbExeOneProject, SiteConfigCodeEnum.L9.toString()));
        //播报扣分不播报扣分项目
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbNoPlayProject, SiteConfigCodeEnum.L12.toString()));
        //随机播报线路
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbRandomPlayLine, SiteConfigCodeEnum.L27.toString()));
        //成绩合格不播报扣分
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbPassNoPlay, SiteConfigCodeEnum.L14.toString()));
        //成绩不合格播报成绩
        checkBoxCommonModels.add(new CheckBoxCommonModel(cbNoPassPlay, SiteConfigCodeEnum.L18.toString()));
        for (CheckBoxCommonModel model : checkBoxCommonModels) {
            model.getCb().setChecked(model.isInitValue());
            model.getCb().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    SignalGConstant.examConfigMap.put(model.getKey(), isChecked);
                    if (isChecked != model.isInitValue()) {
                        tempMap.put(model.getKey(), isChecked);
                    } else {
                        tempMap.remove(model.getKey());
                    }
                }
            });
        }
    }

    @OnClick({R.id.tv_exam_surface, R.id.tv_sczb_next_project, R.id.tv_mndg_next_project, R.id.tv_play_order, R.id.tv_kbtc_project, R.id.tv_exe_one_project, R.id.tv_select_random_line, R.id.tab_speed_count, R.id.tab_12gear_dis, R.id.tab_12gear_dis_noclutch, R.id.tab_gear_speed, R.id.tab_speed_count_c2, R.id.tv_save_param})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_exam_surface:
                siteInfoDialog.showExamTemplateDialog(tvExamSurface, tempMap);
                break;
            case R.id.tv_sczb_next_project: //上车准备后接项目
                siteInfoDialog.showSelectDialog(1, tvSczbNextProject, tempMap);
                break;
            case R.id.tv_mndg_next_project: //模拟灯光后接项目
                siteInfoDialog.showSelectDialog(2, tvMndgNextProject, tempMap);
                break;
            case R.id.tv_play_order:  //播报顺序
                siteInfoDialog.showSelectDialog(3, tvPlayOrder, tempMap);
                break;
            case R.id.tv_kbtc_project: //靠边停车选择项目
                siteInfoDialog.showSelectProjectDialog(1, tempMap);
                break;
            case R.id.tv_exe_one_project: //选中项目只执行一次
                siteInfoDialog.showSelectProjectDialog(2, tempMap);
                break;
            case R.id.tv_select_random_line:  //选择随机播报的线路
                presenter.getChoiceLines(this);
                break;
            case R.id.tab_speed_count:
                if (cbSpeedCount.isChecked()) return;
                setShowC1Status(1);
                break;
            case R.id.tab_12gear_dis:
                if (cb12gearDis.isChecked()) return;
                setShowC1Status(2);
                break;
            case R.id.tab_12gear_dis_noclutch:
                if (cb12gearDisNoclutch.isChecked()) return;
                setShowC1Status(3);
                break;
            case R.id.tab_gear_speed:
                if (cbGearSpeed.isChecked()) return;
                setShowC1Status(4);
                break;
            case R.id.tab_speed_count_c2:
                if (cbSpeedCountC2.isChecked()) return;
                setShowC2Status(1);
                break;
            case R.id.tv_save_param:  //保存
                if (tempMap.size() == 0) return;
                for (String key : tempMap.keySet()) {
                    synExamBean.getExamConfigMap().put(key, tempMap.get(key));
                }
                if (isPartner) {
                    site.setPartneModifyVal(gs.toJson(synExamBean));
                } else {
                    site.setCoachModifyVal(gs.toJson(synExamBean));
                }
                UserDbController.getInstance(false).update(site);
                MessageBox.show(getActivity(), "保存成功!");
                break;
        }
    }

    private void setShowC1Status(int flag) {
        cbSpeedCount.setChecked(flag == 1);
        cb12gearDis.setChecked(flag == 2);
        cb12gearDisNoclutch.setChecked(flag == 3);
        cbGearSpeed.setChecked(flag == 4);
        SignalGConstant.examConfigMap.put(SiteConfigCodeEnum.L21.toString(), flag);
        if (flag != chooseValueC1) {
            tempMap.put(SiteConfigCodeEnum.L21.toString(), flag);
        } else {
            tempMap.remove(SiteConfigCodeEnum.L21.toString());
        }
    }

    private void setShowC2Status(int flag) {
        cbSpeedCountC2.setChecked(flag == 1);
        SignalGConstant.examConfigMap.put(SiteConfigCodeEnum.L25.toString(), flag);
        if (flag != chooseValueC2) {
            tempMap.put(SiteConfigCodeEnum.L25.toString(), flag);
        } else {
            tempMap.remove(SiteConfigCodeEnum.L25.toString());
        }
    }

    @Override
    public void getLineComplete(List<LineInfoEntity> lines) {
        siteInfoDialog.showSelectRandomLine(lines, tempMap);
    }
}